package cn.aylog.controller;

import cn.aylog.plugins.IUsb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Component
public class Computer {

    @Autowired
    private ClassPathXmlApplicationContext context;


    // 记录已安装的插件
    Map<String, IUsb> plugins = new HashMap<>();
    private static final String PATH = "plugins.properties";
    private static Properties props = new Properties();
    static {
        // 加载配置
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(PATH)){
            props.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void installAll() {
        for(String name : props.stringPropertyNames()) {
            Class<IUsb> clazz = null;
            try {
                clazz = (Class<IUsb>) Class.forName(props.getProperty(name));
                plugins.put(name, context.getBean(clazz));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 安装插件
     */
    public void install(String name, IUsb plugin) {
        plugins.put(name, plugin);
    }

    /**
     * 插件工作
     */
    public void doWork() {
        for(IUsb plugin : plugins.values()) {
            plugin.work();
        }
    }



}
